package services

import (
	"errors"
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/debug"
	"goravel/app/http/requests"
	"goravel/app/models"
	"time"
)

type AdminService struct {
}

func (receiver AdminService) Login(ctx http.Context, request requests.LoginRequest) (map[string]any, error) {

	var admin models.Admin

	debug.Dump(facades.Hash().Make("123123"))
	err := facades.Orm().Query().Where("username = ?", request.Username).With("Roles").FindOrFail(&admin)
	if err != nil {
		return nil, errors.New("帐号或密码错误")
	}

	if facades.Hash().Check(request.Password, admin.Password) == false { //密码验证不成功

		return nil, errors.New("帐号或密码错误")
	}
	if admin.Status != 1 {
		return nil, errors.New("帐号已关闭")
	}

	token, err := facades.Auth(ctx).Login(admin)

	facades.Orm().Query().Model(models.Admin{}).Where("id = ?", admin.ID).Update(&models.Admin{
		LoginIp:   ctx.Request().Ip(),
		LoginTime: time.Now(),
	})

	return map[string]any{"admin": admin, "token": token}, err
}
